package com.springboot.demo.web;

import com.springboot.demo.entity.*;
import com.springboot.demo.service.BaseSetupService;
import com.springboot.demo.service.ReaderBRService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Controller
public class ReaderBRController {
    @Autowired
    private ReaderBRService readerBRService;
    @Autowired
    private BaseSetupService baseSetupService;

    //刷新reserve表，删除过期reserve，修改对应book状态并decReaderNum
    @RequestMapping(value = "/refresh", method = RequestMethod.POST)
    @ResponseBody
    public String refresh() throws ParseException {
        Calendar calendarDel = Calendar.getInstance();
        Calendar calendarNow = Calendar.getInstance();
        List<Reserve> listDel = new ArrayList<>();
        String rnameDel;
        String phoneDel;
        long bookidDel;
        listDel.addAll(readerBRService.getReserve());
        for (int i = 0; i < listDel.size() ; i++) {
            calendarDel=readerBRService.StringToTime(listDel.get(i).getStartTime());
            if (readerBRService.TimeMinusTimeMinite(calendarDel,calendarNow)>120) {
                System.out.println("开始删除reserve过期记录");
                phoneDel=listDel.get(i).getPhone();
                bookidDel=listDel.get(i).getID();
                rnameDel=listDel.get(i).getRname();
                readerBRService.deleteReserve(phoneDel, bookidDel);
                readerBRService.decReaderNum(rnameDel,phoneDel);
                readerBRService.updateNotBorrowed(bookidDel);
            }
        }
        return "yes";
    }
    //reserved执行
    @RequestMapping(value = "/reserve",method = RequestMethod.POST)
    @ResponseBody
    public String judge_reader_reserve(@RequestParam("bookid") String bookid1,@RequestParam("rname") String rname,@RequestParam("phone") String phone,@RequestParam("status") String status) throws ParseException {
//        //功能段1：刷新reserve表，删除过期reserve，修改对应book状态并decReaderNum，可在本controller中任意方法中想要刷新reserve的情况下粘贴使用本段代码
//        refresh();
//        //功能段1结束。
        String returnValue = null;
        if(status.equals("reserved")){
            long bookid=Long.parseLong(bookid1);
            List<Reserve> listR1 = new ArrayList<>();
            listR1.addAll(readerBRService.getReserveByRPB(rname, phone, bookid));
            if(listR1.size()==0){
                System.out.println("不是你reserve的,是别人reserve的");
                returnValue="no2";
            }
            else{
                System.out.println("是你reserve的,是否正式发出borrow申请？");
                returnValue="yes2";
            }
        } else if(status.equals("not borrow")){
            long bookid=Long.parseLong(bookid1);
            Calendar calendar = Calendar.getInstance();
            List<Reader> listR1 = new ArrayList<>();
            listR1 = readerBRService.getReaderByNP(rname, phone);
            if(listR1.get(0).getNumber()==3){
                System.out.println("已满3本，无法reserve");
                returnValue = "no1";
            }
            else if(listR1.get(0).getNumber()<3) {
                System.out.println("允许reserve");
                String startTime1 = readerBRService.TimeToString(calendar);
                readerBRService.insertReserve(phone, bookid, rname, startTime1);
                readerBRService.updateReserved(bookid);
                readerBRService.incReaderNum(rname, phone);
                System.out.println("已经reserve");
                returnValue = "yes1";
            }
        }

        return returnValue;
    }
    //borrowed状态，判断是否是自己借阅的
    @RequestMapping(value = "/borrowed",method = RequestMethod.POST,params = {"status=borrowed"})
    @ResponseBody
    public String judge_reader_borrowed(@RequestParam("bookid") String bookid1,@RequestParam("rname") String rname,@RequestParam("phone") String phone,@RequestParam("status") String status) throws ParseException {
        String returnValue = null;
        long bookid=Long.parseLong(bookid1);
        List<BorrowMsg> listB1 = new ArrayList<>();
        listB1.addAll(readerBRService.getBorrowingB(phone,rname,bookid));
        if(listB1.size()==0){
            System.out.println("不是你borrow的，是别人borrow的");
            returnValue="no";
        }
        else{
            System.out.println("是你borrow的,是否正式发出return申请？");
            returnValue="yes";
        }
        return returnValue;
    }
    //borrowing判断
    @RequestMapping(value = "/borrowing",method = RequestMethod.POST,params = {"status=borrowing"})
    @ResponseBody
    public String judge_reader_borrowing(@RequestParam("bookid") String bookid1,@RequestParam("rname") String rname,@RequestParam("phone") String phone,@RequestParam("status") String status) throws ParseException {
        String returnValue = status;
        long bookid=Long.parseLong(bookid1);
        List<BorrowMsg> listB1 = new ArrayList<>();
        listB1.addAll(readerBRService.getBorrowingA(phone,rname,bookid));
        if(listB1.size()==0){
            System.out.println("不是你申请borrow的，是别人申请borrow的");
            returnValue="no";
        }
        else{
            System.out.println("是你申请borrow的,请等待librarian处理");
            returnValue="yes";
        }
        return returnValue;
    }

    //borrow执行
    @RequestMapping(value = "/borrow",method = RequestMethod.POST)
    @ResponseBody
    public String do_reader_borrow(@RequestParam("bookid") String bookid1,@RequestParam("rname") String rname,@RequestParam("phone") String phone,@RequestParam("status") String status) throws ParseException {
        String returnValue = "";
        long bookid=Long.parseLong(bookid1);
        Calendar calendar = Calendar.getInstance();
        List<Reader> listR1 = new ArrayList<>();
        List<Reserve> listR2 = new ArrayList<>();

        if(status.equals("not borrow")){
            listR1 = readerBRService.getReaderByNP(rname, phone);
            if(listR1.get(0).getNumber()==3){
                System.out.println("已满3本，无法borrow");
                returnValue = "no1";
            }
            else if(listR1.get(0).getNumber()<3) {
                System.out.println("允许borrow");
                String startTime2=readerBRService.TimeToString(calendar);
                readerBRService.insertBorrow(phone,rname,bookid,startTime2);
                readerBRService.updateBorrowing(bookid);
                readerBRService.incReaderNum(rname, phone);
                readerBRService.deleteReserve(phone,bookid);
                System.out.println("已经向librarian发出申请borrow");
                returnValue = "yes1";
            }
        }else if(status.equals("reserved")){
            //段2：用于执行borrow前，防止borrow自己已经reserve的书时产生逻辑bug
            listR2.addAll(readerBRService.getReserveByRPB(rname,phone,bookid));
            if(listR2.size()>0){
                readerBRService.deleteReserve(phone, bookid);
                readerBRService.decReaderNum(rname,phone);
            }
            //段2结束
            System.out.println("允许borrow");
            String startTime2=readerBRService.TimeToString(calendar);
            readerBRService.insertBorrow(phone,rname,bookid,startTime2);
            readerBRService.updateBorrowing(bookid);
            readerBRService.incReaderNum(rname, phone);
            readerBRService.deleteReserve(phone,bookid);
            System.out.println("已经向librarian发出申请borrow");
            returnValue = "yes2";
        }
        return returnValue;
    }
    //return执行
    @RequestMapping(value = "/returnbook",method = RequestMethod.POST)
    @ResponseBody
    public String do_reader_return(@RequestParam("bookid") String bookid1,@RequestParam("rname") String rname,@RequestParam("phone") String phone,@RequestParam("status") String status) throws ParseException {
        String returnValue = status;
        long bookid=Long.parseLong(bookid1);
        List<BorrowMsg> list1 = new ArrayList<>();
        List<ReturnMsg> list2 = new ArrayList<>();
        Calendar calendarStart = Calendar.getInstance();
        Calendar calendarEnd = Calendar.getInstance();
        String overDue;
        long Days;
        long fine;
        long BaseRT = baseSetupService.getRTValue();
        long Basefine = baseSetupService.getFineValue();
        String dateStart;
        String dateEnd;
        //根据phone与rname与bookid从borrow表中取已经在borrowing(借阅中)状态的book的信息，可用于操作申请return
        list1.addAll(readerBRService.getBorrowingB(phone, rname,bookid));
        //先判断是否已经向returntable发送过申请
        list2.addAll(readerBRService.getReturningPB(phone,bookid));
        if(list2.size()==0) {
            //向return表中添加return申请信息
            calendarStart = readerBRService.StringToTime(list1.get(0).getStarttime());
            dateStart = readerBRService.TimeToString(calendarStart);
            dateEnd = readerBRService.TimeToString(calendarEnd);
            Days = readerBRService.TimeMinusTimeDay(calendarStart, calendarEnd);
            System.out.println(Days);
            if (Days >= BaseRT) {
                fine = (Days - BaseRT)*Basefine;
                overDue = "yes";
                readerBRService.insertReturn(phone, bookid, dateStart, dateEnd, overDue, Days, fine);
                readerBRService.decReaderNum(rname, phone);
            } else {
                overDue = "no";
                readerBRService.insertReturn(phone, bookid, dateStart, dateEnd, overDue, Days, 0);
                readerBRService.decReaderNum(rname, phone);
            }
            System.out.println("已向librarian发出return申请");
            returnValue = "yes";
        }else{
            returnValue = "no";
        }
        return returnValue;
    }
}